package zq.cn.utils;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZQ on 2016/4/18.
 */
public class SqlDao {
    public static void insertData(Map<String,Object> map) {
        String sql = "insert into txt_tab(question,answer) values(?,?)";
        Globals.sql.getWritableDatabase().execSQL(sql, new Object[]{map.get("question"), map.get("answer")});
    }

    public static List<Map<String, Object>> ViewAllData() {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "select id,question,answer from txt_tab";
        Cursor cur = Globals.sql.getReadableDatabase().rawQuery(sql, null);
        cur.moveToFirst();
        while(!cur.isAfterLast()) {
            Map<String, Object> map = new HashMap<>();
            map.put("question","["+cur.getInt(0)+"]"+cur.getString(1));
            map.put("answer", cur.getString(2));
            list.add(map);
            cur.moveToNext();
        }
        cur.close();
        return list;
    }

    public static List<Map<String, Object>> ViewPageData(int pagenum,int pagesize,String keyword) {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "select id,question,answer from txt_tab where question like ? limit ?,?";
        Cursor cur = Globals.sql.getReadableDatabase().rawQuery(sql, new String[]{"%"+keyword+"%", (pagenum*pagesize-pagesize)+"", pagesize+""});
        cur.moveToFirst();
        while(!cur.isAfterLast()) {
            Map<String, Object> map = new HashMap<>();
            map.put("question","["+cur.getInt(0)+"]"+cur.getString(1));
            map.put("answer", cur.getString(2));
            map.put("flag",false);
            list.add(map);
            cur.moveToNext();
        }
        cur.close();
        return list;
    }

    public static void deleteData() {
        String sql = "delete from txt_tab";
        Globals.sql.getWritableDatabase().execSQL(sql);
    }

    public static int getCound(String keyword) {
        int count=0;
        String sql = "select count(*) from txt_tab where question like ?";
        Cursor cur = Globals.sql.getReadableDatabase().rawQuery(sql, new String[] {"%"+keyword+"%"});
        cur.moveToFirst();
        count = cur.getInt(0);
        cur.close();
        return  count;
    }
}
